<template>
  <div class="students-sign-up">
    <GoBack :title="title" />
    <div class="sign-up-studentInfo">
      <el-autocomplete
        v-model="searchName"
        :fetch-suggestions="toGetCurrentStudentsList"
        placeholder="请输入学员姓名/手机号快速查找"
        @select="handleSelect"
        style="width: 300px"
        clearable
        :trigger-on-focus="false"
      >
        <template #suffix>
          <el-icon class="el-input__icon" @click="handleIconClick">
            <edit />
          </el-icon>
        </template>
        <template #default="{ item }">
          <span>{{ item.name }}</span>
          <span
            style="
              margin-left: 10px;
              margin-right: 40px;
              font-size: 14px;
              color: #3bbdaa;
            "
            >{{
              item.stage === 1
                ? "意向"
                : item.stage === 2
                ? "在读"
                : item.stage === 3
                ? "跟进"
                : item.stage === 4
                ? "报读"
                : item.stage === 5
                ? "历史"
                : "未知"
            }}</span
          >
          <span>{{ item.mobile }}</span>
        </template>
      </el-autocomplete>
      <div class="studentInfo" v-if="studentsId">
        <span class="type">{{
          studentsDetails.stage === 1
            ? "意向学员"
            : studentsDetails.stage === 2
            ? "在读学员"
            : studentsDetails.stage === 3
            ? "跟进学员"
            : studentsDetails.stage === 4
            ? "报读学员"
            : studentsDetails.stage === 5
            ? "历史学员"
            : "未知状态"
        }}</span>
        <span class="name">{{ studentDetails.name }}</span>
        <el-icon v-if="studentDetails.gender == '1'" style="color: #fb6465"
          ><Female
        /></el-icon>
        <el-icon v-else-if="studentDetails.gender == '0'" style="color: #4791ed"
          ><Male
        /></el-icon>
        <span class="mobile"
          >{{ studentDetails.mobile }}({{
            studentsDetails.familyRel === "无" ||
            studentsDetails.familyRel === "0"
              ? "家长"
              : studentsDetails.familyRel
          }})</span
        >
        <div class="lesson">
          <el-dropdown>
            <span class="el-dropdown-link">
              <span style="color: #666; font-size: 16px">报读课程:</span>
              <el-icon
                class="el-icon--right"
                style="color: #666; font-size: 16px"
              >
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="(item, key) in studentDetails.courses"
                  :key="key"
                  >{{ item }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <span>消费金额: ¥ {{ studentDetails.spendAmount }}</span>
        <div v-if="studentDetails.exceedingClass > 0" class="beyound">
          超上课时:
          <span style="color: rgb(248, 152.1, 152.1)">{{
            Math.abs(studentDetails.exceedingClass)
          }}</span>
          课时
        </div>
      </div>
    </div>
    <div class="isStudent-placeholder" v-if="!studentsId">
      <div class="ph-image"></div>
      <div class="text">请先从左上角搜索转出学员</div>
    </div>
    <div class="sign-up-choose" v-else>
      <p style="font-weight: bold; font-size: 18px">退课信息</p>
      <span class="search-label" style="margin-right: 10px"> 退出课程:</span>
      <el-select
        v-model="courseName"
        placeholder="请选择退出课程"
        style="width: 240px"
        @change="toSearchOrder"
        clearable
      >
        <el-option
          v-for="item in courseList"
          :key="item.id"
          :label="item.courseName"
          :value="item.id"
        />
      </el-select>
      <el-table
        ref="multipleTableRef"
        :data="orderList"
        style="width: 100%; margin: 20px 0 50px"
        @selection-change="handleSelectionOrder"
        v-loading="loading"
      >
        <el-table-column
          label="订单号"
          fixed="left"
          width="155"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            <span style="color: #67c23a; cursor: pointer">{{
              scope.row.orderNo
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="单价"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            ¥{{ scope.row.originalUnitPrice }}
          </template>
        </el-table-column>
        <el-table-column
          label="购买项目"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        >
          <template #default="scope">
            {{ scope.row.courseName }}
          </template>
        </el-table-column>
        <el-table-column
          label="定价标准"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        >
          <template #default="scope">
            {{ scope.row.coursePriceName }}
          </template>
        </el-table-column>
        <el-table-column
          property="addTime"
          label="创建时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />
        <el-table-column
          label="购买数量"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            {{ scope.row.countLessonTotalNormal }}课时
          </template>
        </el-table-column>
        <el-table-column
          label="赠送数量"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            {{ scope.row.countLessonTotalGive }}课时
          </template>
        </el-table-column>
        <el-table-column
          label="总价"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope"> ¥{{ scope.row.courseAmount }} </template>
        </el-table-column>
        <el-table-column
          label="直减/折扣"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            ¥ {{ scope.row.courseAmount - scope.row.discountAmount }}
          </template>
        </el-table-column>
        <el-table-column
          label="小计"
          show-overflow-tooltip
          :formatter="formatName"
        >
          <template #default="scope">
            ¥ {{ scope.row.discountAmount }}
          </template>
        </el-table-column>
        <el-table-column label="剩余" align="center">
          <el-table-column
            label="剩余购买数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.remainderLessonNormal }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="剩余赠送数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.remainderLessonGive }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="剩余金额"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              ¥{{ scope.row.remainderAmount }}
            </template>
          </el-table-column>
        </el-table-column>
        <!-- <el-table-column label="转出" align="center">
          <el-table-column
            label="转出购买数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.coursePriceName }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="转出赠送数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.coursePriceName }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="转出金额"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.coursePriceName }}课时
            </template>
          </el-table-column>
        </el-table-column> -->
        <el-table-column
          type="selection"
          width="100"
          align="center"
          fixed="right"
        />
      </el-table>
      <div class="price">
        <span>应退金额:</span>
        <span class="price-num">¥{{ outMoney ? outMoney : "0.00" }}</span>
      </div>
    </div>
    <div class="sign-up-otherInfo">
      <div>其他信息</div>
      <el-divider />
      <div class="form">
        <el-form
          :model="orderInfoForm"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item label="支付方式" prop="classType">
            <el-select
              style="width: 220px"
              v-model="payType"
              placeholder="请选择支付方式"
              clearable
            >
              <el-option
                v-for="item in classTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button
              style="padding: 0 10px"
              type="primary"
              link
              @click="openClassType = true"
            >
              新增
            </el-button>
          </el-form-item>
          <el-form-item label="经办日期">
            <el-date-picker
              v-model="orderInfoForm.handlingTime"
              type="date"
              placeholder="请选择经办日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderInfoForm.remarks" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="margin-top: 50px"></div>
    <div class="submit">
      <el-button type="primary" @click="toRefundOrder">确认退课</el-button>
    </div>
    <!-- 创建支付方式 -->
    <el-dialog v-model="openClassType" title="支付方式设置" width="500">
      <el-button @click="handleAddClassType" type="primary"> 添加 </el-button>
      <el-form ref="classTypeRef" :model="classTypeForm" label-width="auto">
        <el-table
          class="quotation"
          :data="classTypeForm.copyClassTypeList"
          style="width: 100%; margin-top: 20px"
          max-height="400"
        >
          <el-table-column prop="name" label="支付方式名称">
            <template #default="scope">
              <el-form-item
                :prop="`copyClassTypeList.${scope.$index}.name`"
                :rules="[
                  {
                    required: true,
                    message: '请输入支付名称',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="handleDeleteClassType(scope.$index)"
                v-if="scope.row.used === '0'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClassTypeList()">取消</el-button>
          <el-button type="primary" @click="updateClassTypeList()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getStudentsList,
  getStudentsInfo,
  getStudentInfo,
  getLessonList,
  getPerformanceList,
  toApplication,
  getAllStudent,
  getCourseList,
  getCourseOrderList,
  refundOrderAPI,
} from "@/api/studentManagement/index.js";
import {
  getTLabelListAPI,
  updateTLabelListAPI,
} from "@/api/registrar/classroom";
import { onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import GoBack from "@/components/GoBack/index.vue";

// import CreateStudents from '../components/createStudents/index.vue'
const { proxy } = getCurrentInstance();

//接收学员ID
const route = useRoute();
const studentsId = ref(route.params.studentsId);
const title = route.meta.title;

onMounted(() => {
  if (studentsId.value) {
    console.log("444", studentsId);

    // 处理有学生 ID 的情况
    toGetStudentsInfo();
    toGetStudentInfo();
  }
});
//返回按钮
const router = useRouter();
const goBack = () => {
  router.go(-1);
};

const studentsInfo = ref({}); //传给dialog的值
const type = ref("");

//查找学员
const searchName = ref(""); //搜索学员名字
const toGetCurrentStudentsList = async (queryString, cb) => {
  if (queryString) {
    const params = {
      param: queryString,
    };
    try {
      const res = await getAllStudent(params);
      if (res.code === 200) {
        // 确保有多个结果
        const students = res.data;
        cb(students);
      } else {
        cb([]); // 如果没有找到结果，传递空数组
      }
    } catch (error) {
      console.error("获取学生列表失败:", error);
      cb([]); // 出错时返回空建议
    }
  }
};
const handleSelect = (item) => {
  searchName.value = null;
  console.log("Selected:", item);
  studentsId.value = item.id;
  toGetStudentsInfo();
  toGetStudentInfo();
  toGetCourseList();
};
//获取学员详细信息
const studentsDetails = ref({});
const toGetStudentsInfo = async () => {
  // console.log('iooooo',proxy.addDateRange(value1.value,[]));
  const params = {
    id: studentsId.value,
  };
  try {
    const res = await getStudentsInfo(params);
    if (res.code == 200) {
      studentsDetails.value = res.data;
      studentsDetails.value.gender = String(studentsDetails.value.gender);
      studentsDetails.value.defaultFamilyRel =
        studentsDetails.value.defaultUser.familyRel;
      studentsDetails.value.defaultMobile =
        studentsDetails.value.defaultUser.mobile;
      if (studentsDetails.value.backupUser) {
        studentsDetails.value.backFamilyRel =
          studentsDetails.value.backupUser.familyRel;
        studentsDetails.value.backMobile =
          studentsDetails.value.backupUser.mobile;
      }
    }
  } catch (error) {
    console.error("获取学生详情信息失败:", error);
  }
};
// onBeforeMount(toGetStudentsInfo)
//获取学员基本信息
const studentDetails = ref({});
const toGetStudentInfo = async () => {
  const params = {
    id: studentsId.value,
    // id: 38,
  };
  try {
    const res = await getStudentInfo(params);
    if (res.code == 200) {
      studentDetails.value = res.data;
      console.log("888888", studentDetails);
    }
  } catch (error) {
    console.error("获取学生的基本信息失败:", error);
  }
};
// onBeforeMount(toGetStudentInfo)

//支付方式部分
const loading = ref(false);
const payType = ref("");
const openClassType = ref(false);
const classTypeList = ref([]);
const classTypeForm = ref({
  copyClassTypeList: [],
});
function getClassTypeList() {
  loading.value = true;
  getTLabelListAPI({ lableType: "pay_type" }).then((response) => {
    classTypeList.value = response.data;
    classTypeForm.value.copyClassTypeList = [...response.data];
    loading.value = false;
  });
}
onMounted(getClassTypeList);
function handleAddClassType() {
  classTypeForm.value.copyClassTypeList.push({
    id: undefined,
    name: "",
    lableType: "pay_type",
    used: "0",
  });
}
function handleDeleteClassType(index) {
  classTypeForm.value.copyClassTypeList.splice(index, 1);
}
function cancelClassTypeList() {
  classTypeForm.value.copyClassTypeList = [...classTypeList.value];
  openClassType.value = false;
}
function updateClassTypeList() {
  proxy.$refs["classTypeRef"].validate((valid) => {
    if (valid) {
      loading.value = true;
      updateTLabelListAPI(classTypeForm.value.copyClassTypeList).then(() => {
        loading.value = false;
        openClassType.value = false;
        getClassTypeList();
      });
    } else {
      proxy.$modal.msgError("支付方式不可为空过，请检查后再提交");
    }
  });
}
//处理日期格式
const formatDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
//其他信息部分
const orderInfoForm = ref({
  handlingTime: formatDate(),
  remarks: "",
});
const saleList = ref([]);
//添加表格
const toAddItem = () => {
  saleList.value.push({
    saler: "",
    courseAmount: "",
  });
};
//删除表格
const handleDeletePeople = (index) => {
  saleList.value.splice(index, 1);
};
//获取工作人员下拉列表
const followPeopleList = ref([]);
const toFollowPeopleList = async () => {
  try {
    const res = await getPerformanceList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      followPeopleList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学员创建人下拉列表失败:", error);
  }
};
onMounted(toFollowPeopleList);

//退课部分--------------------------------------------------------------------------------------------------------------
//获取转出课程下拉列表
const courseName = ref(null);
const courseList = ref([]); //转出课程下拉列表
const toGetCourseList = async () => {
  try {
    const res = await getCourseList({ studentId: studentsId.value });
    if (res.code == 200) {
      courseList.value = res.data;
      courseName.value = res.data[0].id;
      toGetCourseOrderList();
    }
  } catch (error) {
    console.error("获取转出课程下拉列表失败:", error);
  }
};
// onMounted(toGetCourseList)
const toSearchOrder = () => {
  toGetCourseOrderList();
};
//获取学员所报读课程对应的订单列表
const orderList = ref([]);
const toGetCourseOrderList = async () => {
  try {
    const res = await getCourseOrderList({
      studentId: studentsId.value,
      courseId: courseName.value,
    });
    if (res.code == 200) {
      orderList.value = res.data;
    }
  } catch (error) {
    console.error("获取转出课程下拉列表失败:", error);
  }
};
// onMounted(toGetCourseOrderList)
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};
//选择退订项目
const outMoney = ref(null);
let selectOrder = [];
const handleSelectionOrder = (val) => {
  selectOrder = val;
  outMoney.value = null;
  selectOrder.forEach((item) => {
    outMoney.value += item.remainderAmount;
  });
  console.log("selectOrder----------", selectOrder);
};
//退课
const toRefundOrder = () => {
  if (selectOrder.length) {
    ElMessageBox.confirm("确定退课吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        let beyondLesson = [];
        selectOrder.map((item) => {
          if (item.remainderAmount < 0) {
            beyondLesson.push(item.remainderAmount);
          }
        });
        if (!beyondLesson.length) {
          const updatedOrders = selectOrder.map((item) => ({
            ...item,
            refundLessonNormal: item.remainderLessonNormal,
            refundLessonGive: item.remainderLessonGive,
            refundAmount: item.remainderAmount,
            handlingTime: orderInfoForm.value.handlingTime,
            studentId: studentsId.value,
            courseId: courseName.value,
            remark: orderInfoForm.value.remarks,
          }));
          try {
            const res = await refundOrderAPI(updatedOrders);
            if (res.code == 200) {
              ElMessage({
                type: "success",
                message: "退课成功",
              });
              router.push({
                name: "OrderList",
              });
            }
          } catch (error) {
            console.error("退课失败:", error);
          }
        } else {
          ElMessage({
            type: "error",
            message: "该学员所选课程下有超上课时,无法进行退课,请重新选择 ",
          });
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消退课",
        });
      });
  } else {
    ElMessage({
      type: "error",
      message: "请选择退出课程",
    });
  }
};
</script>

<style lang="scss" scoped>
.students-sign-up {
  height: 100%;
  overflow: auto;
  .sign-up-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    margin-bottom: 25px;
    width: 150px;
    // background-color: red;
    color: #989898;
    .sign-up-back {
      display: flex;
      align-items: center;
      cursor: pointer;
    }
  }
  .sign-up-studentInfo {
    padding: 0 10px 20px 10px;
    margin-bottom: 20px;
    box-shadow: 5px 5px 5px rgb(213, 217, 208);
    .studentInfo {
      margin-top: 20px;
      border: 1px solid #e8e8e8;
      padding: 10px;
      font-size: 16px;
      color: #666;
      .type {
        display: inline-block;
        padding: 0 12px;
        margin-right: 20px;
        font-size: 14px;
        color: #3bbdaa;
        border: 1px solid #3bbdaa;
      }
      .name {
        color: #333;
        font-size: 18px;
        margin-right: 20px;
      }
      .mobile {
        font-size: 16px;
        color: #666;
        margin-left: 20px;
      }
      .lesson {
        display: inline-block;
        padding: 7px 30px;
        border-left: 1px solid #e8e8e8;
        border-right: 1px solid #e8e8e8;
        margin: 0 20px;
      }
      .beyound {
        display: inline-block;
        padding: 7px 30px;
        border-left: 1px solid #e8e8e8;
        // border-right: 1px solid #e8e8e8;
        margin: 0 20px;
      }
    }
  }
  .isStudent-placeholder {
    padding: 20px 10px;
    margin-bottom: 20px;
    box-shadow: 5px 5px 5px rgb(213, 217, 208);

    .ph-image {
      width: 240px;
      height: 110px;
      margin: 0 auto;
      background-image: url("@/assets/images/1571657090939.png"); /* 设置背景图片 */
      background-size: cover; /* 背景图片覆盖整个容器 */
      background-position: center; /* 背景图片居中显示 */
      background-repeat: no-repeat; /* 背景图片不重复 */
    }
    .text {
      text-align: center;
      color: #333;
      font-size: 16px;
    }
  }
  .sign-up-choose {
    padding: 20px 10px;
    margin-bottom: 20px;
    box-shadow: 5px 5px 5px rgb(213, 217, 208);
    .price {
      display: flex;
      justify-content: end;
      align-items: center;
      margin-top: 20px;
      padding: 10px;
      .price-num {
        color: #409eff;
        font-size: 18px !important;
        margin-left: 10px;
        font-size: 18px;
      }
    }
    .content {
      margin-top: 30px;
      // background-color: blue;
      .isLesson-placeholder {
        .ph-image {
          width: 240px;
          height: 110px;
          margin: 0 auto;
          background-image: url("@/assets/images/phImage.png"); /* 设置背景图片 */
          background-size: cover; /* 背景图片覆盖整个容器 */
          background-position: center; /* 背景图片居中显示 */
          background-repeat: no-repeat; /* 背景图片不重复 */
        }
        .text {
          text-align: center;
          color: #333;
          font-size: 16px;
        }
      }
      .lesson-table {
        .coupon {
          margin-top: 20px;
          color: #333;
          font-size: 14px;
          .coupon-box {
            padding: 20px;
            margin-top: 10px;
            border: 1px solid #e8e8e8;
          }
        }
        // .price {
        //   display: flex;
        //   justify-content: end;
        //   align-items: center;
        //   margin-top: 20px;
        //   padding: 10px;
        //   .price-num {
        //     margin-left: 10px;
        //     font-size: 18px;
        //   }
        // }
      }
    }
  }
  .sign-up-otherInfo {
    padding: 10px;
    box-shadow: 5px 5px 5px rgb(213, 217, 208);
    .form {
      padding-left: 100px;
    }
  }
  .submit {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    // height: 50px;
    padding: 10px 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    background-color: #fff;
  }
}
</style>
<style lang="scss">
// :deep(.example-showcase .el-dropdown + .el-dropdown) {
//   margin-left: 15px;
// }
// :deep(.example-showcase .el-dropdown-link) {
//   cursor: pointer;
//   color: var(--el-color-primary);
//   display: flex;
//   align-items: center;
//   background-color: red;
// }

// :deep(.el-dropdown-menu:focus-visible) {
//   outline: none;
// }
</style>
